package common

import (
	"context"
	"fmt"
	"git.mycaigou.com/gfyx/common/rpc_client"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/infrastructure/common/constants"
	opptyCommonPb "git.mycaigou.com/gfyx/micro-gfyx-mp-api/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/common"
	microGfyxUserService "git.mycaigou.com/gfyx/micro-gfyx-mp-api/proto/micro_gfyx_user_service_proto/micro-gfyx-user-service"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/service/common/file"
)

type fileRepository struct{}

func (o *fileRepository) SaveToFile(ctx context.Context, ossFilePath, fileType, fileName, business string, size int64, isPrivate int64, tenantCode string) (string, error) {
	if tenantCode == "" {
		//保存至非租户服务
		request := &microGfyxUserService.SaveToFileRequest{
			FilePath:   ossFilePath,
			FileType:   fileType,
			Business:   business,
			FileSize:   size,
			FileName:   fileName,
			IsPrivate:  isPrivate,
			TenantCode: tenantCode,
		}
		conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_USER_SERVICE)
		if err != nil {
			return "", err
		}
		defer func() {
			_ = conn.Close()
		}()

		client := microGfyxUserService.NewFileServiceClient(conn)
		res, err := client.SaveToFile(ctx, request)
		if err != nil {
			return "", err
		}
		return res.FileUid, nil
	} else {
		// 保存至租户服务
		request := &opptyCommonPb.SaveToFileRequest{
			FilePath: ossFilePath,
			FileType: fileType,
			Business: business,
			FileSize: size,
			FileName: fileName,
		}
		conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_OPPTY_SERVICE)
		if err != nil {
			return "", err
		}
		defer func() {
			_ = conn.Close()
		}()

		client := opptyCommonPb.NewFileServiceClient(conn)
		res, err := client.SaveToFile(ctx, request)
		if err != nil {
			return "", err
		}
		return fmt.Sprintf("%d", res.FileId), nil
	}
}

// NewFileRepository
// 构造函数
func NewFileRepository() file.FileRepositoryIface {
	return &fileRepository{}
}
